package com.zhixun.mobile.modules.jiujiudevice.common;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.data.domain.Page;


public class JsonResult {
	private String code;
	private String message;
	private Object data;
	
	/**
	 * 总页数
	 */
	private Integer pageCount;
	/**
	 * 每页显示多少条
	 */
	private Integer pageSize;
	/**
	 * 总记录数
	 */
	private Long count;
	/**
	 * 第几页
	 */
	private Integer page;
	
	
	public Integer getPageCount() {
		return pageCount;
	}

	/**
	 * 构造私有化
	 */
	private JsonResult() {
	}

	public synchronized static String toJson(JsonResult result) {
		ObjectMapper mapper = new ObjectMapper();
		mapper.setSerializationInclusion(Include.NON_NULL);
		String json = null;
		try {
			json = mapper.writeValueAsString(result);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return json;
	}

	public static String Result(ResultCode code) {

		JsonResult result = new JsonResult();
		result.code = code.val();
		return toJson(result);
	}

	public static String Result(ResultCode code, String message) {
		JsonResult result = new JsonResult();
		result.code = code.val();
		result.message = message;
		return toJson(result);
	}

	public static String Result(ResultCode code, String message, Object data) {
		JsonResult result = new JsonResult();
		result.setCode(code);
		result.setMessage(message);
		 //根据不同的结果 做处理
		 if(data instanceof Page){
			 //添加分页
			 Page page = (Page)data;
			 result.setPageCount(page.getTotalPages()); //总页数
			 result.setPageSize(page.getSize()); //每页显示多少条
			 result.setPage(page.getNumber());//第几页
			 result.setData(page.getContent()); //内容
			 result.setCount(page.getTotalElements()); //总条数
			 System.out.println("TotalElements=" + page.getTotalElements());
		 }else{
			 result.setData(data);
		 }

		return toJson(result);
	}

	public void setPageCount(Integer pageCount) {
		this.pageCount = pageCount;
	}

	public Integer getPage() {
		return this.page;
	}

	public void setPage(Integer page) {
		this.page = page;
	}

	public String getCode() {
		return this.code;
	}

	public void setCode(ResultCode code) {
		this.code = code.val();
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public Object getData() {
		return this.data;
	}

	public void setData(Object data) {
		this.data = data;
	}

	public Integer getPageSize() {
		return pageSize;
	}

	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public Long getCount() {
		return count;
	}

	public void setCount(Long count) {
		this.count = count;
	}
	
}
